package com.izocen.rules.assembler;

import org.apache.commons.lang.StringUtils;

import com.izocen.rules.assembler.operator.OperatorChain;
import com.izocen.rules.assembler.operator.chain.AbstractOperator;
import com.izocen.rules.common.ResponseMessage;

/**
 * 
 * @author pengyongjun
 *
 *desc // ( alarmId == 123 or clearFlag != 0 ) and alarmText contains 测试  and alarmTitle notcontains 测试 and alarmLevel in [1,2,3] and alarmStatus  notin [4,5,6] and alarmCount > 45 and alarmTotal < 32 and alarmRegion range [0,3] and alarmProvince norange {4,9}
 */
public class ExpressAssembler {
	
	private ExpressAssembler() {
		
	}
	
	private static ExpressAssembler ea = new ExpressAssembler();
	
	public static ExpressAssembler getInstance() {
		return ea;
	}
	
	/**根据用户提供的自定义表达式，转化成规则引起能够识别的表达式
	 * 也可称为规则解析过程
	 * @param express 用户设置的表达式
	 * @return
	 */
	public ResponseMessage<String> assemble(String  express) {
		if(StringUtils.isBlank(express)) {
			return ResponseMessage.fail("表达为空");
		}
		String tempStr = new String(express);
	    //去掉所有的 小括号 获取单纯的每一个算子
		tempStr = tempStr.replaceAll("[()]", "");//
		String[] operatorArr = tempStr.split(" and | or");//单个算子集合
		AbstractOperator op = OperatorChain.getChain();
		try {
			for(String operator : operatorArr) {//循环处理单个算子
				operator = operator.trim();
				String newOpertor = new String(operator);
				newOpertor = op.handle(newOpertor);//走算子处理链
				//完成后替换
				express = express.replace(operator, newOpertor);
			}
		}catch (Exception e) {
			return ResponseMessage.fail(e.getMessage());
		}
		//替换逻辑标识
		express = express.replaceAll("and", "&&");
		express = express.replaceAll( "or", "||");
		
		return ResponseMessage.succ(express);
	}
	
	
	/*public static void main(String[] args) {
		String express = "( alarmId == '123' or clearFlag != '0' ) and alarmTitle contains 'xd21' and alarmText notcontains 'Jzdd' and alarmCount in ['45','xx22','23'] ";
		
		ExpressAssembler ea = ExpressAssembler.getInstance();
		ResponseMessage<String> rm = ea.assemble(express);
		System.out.println(rm.getMsg());
		System.out.println(rm.getData());
		
	}*/
	
	
	
}


























